package com.season.other.file;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * 文件处理相关工具类
 */
public class FileUtil {

    public static void main(String[] args) throws Exception {
        ArrayList<String> list = new ArrayList<String>() {{
            add("F:\\1.json");
            add("F:\\2.json");
            add("F:\\3.json");
            add("F:\\4.json");
            add("F:\\5.json");
        }};
        for (String parth : list) {
            FileUtil.repalce(parth,"},","},\n");
            System.out.println("file has repalce.");
        }
    }

    // 对文件进行文本替换
    public static void repalce(String path, String src, String target) throws Exception {
        String data = read(path);
        data = data.replace(src, target);
        write(path, data);
    }

    public static String read(String path) throws Exception {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        FileInputStream inputStream = new FileInputStream(file);
        int length = inputStream.available();
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        inputStream.close();
        String str = new String(bytes, StandardCharsets.UTF_8);
        return str;
    }

    public static void write(String path, String data) {
        try {
            String content = data;
            File file = new File(path);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
